﻿#region  
//=====================================================
// 文件名:      FrameWorkEntiy                
// 创建者:      岳智伟                
// 创建时间:    2020/11/09/ 17:06:59              	
// Email:       854426372@qq.com               
// 描述:        当前脚本的功能              
// 修改者列表:  修改者名字以及修改功能      
// 版权所有:    个人独立                 
//======================================================
#endregion 

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace YFrameWork.RunTime
{
    /// <summary>
    /// 模块管理类
    /// </summary>
    public class GameEntry : MonoSingleton<GameEntry>
    {
        /// <summary>
        /// 所有模块管理器的链表
        /// </summary>
        private LinkedList<YFrameWorkComponent> m_Managers = new LinkedList<YFrameWorkComponent>();
        public new T GetComponent<T>() where T : YFrameWorkComponent
        {
            return GetComponent<T>(this.transform);
        }
   
        public  T GetComponent<T>(Transform parent) where T : YFrameWorkComponent
        {
            Type manageType = typeof(T);
            foreach (var item in m_Managers)
            {
                if (item.GetType() == manageType)
                {
                    return item as T;
                }
            }
            T t = CreateManager<T>(manageType) as T;
            t.transform.SetParent(parent);
            return t;
        }
        public YFrameWorkComponent CreateManager<T>(Type manager) where T :UnityEngine.Component
        {
            Component t  =  GameObject.FindObjectOfType<T>();
            if (t == null)
            {
                t = new GameObject(typeof(T).ToString().Replace("YFrameWork.RunTime.",string.Empty).Replace("Component",string.Empty)).AddComponent<T>();
            }
            YFrameWorkComponent man = t as YFrameWorkComponent;
            if (man == null)
            {
                Log.Error("模块管理器创建失败：" + manager.GetType().Name);
            }
            LinkedListNode<YFrameWorkComponent> current = m_Managers.First;
            while (current != null)
            {
                if (man.Priority > current.Value.Priority)
                {
                    break;
                }
                current = current.Next;
            }
            if (current != null)
            {
                m_Managers.AddBefore(current, man);
            }
            else
            {
                m_Managers.AddLast(man);
            }
            man.ToCreate();
            return man;
        }


    

        private void OnDestroy()
        {
            foreach (var item in m_Managers)
            {
                item.Shutdown();
            }
        }

    }
}